package com.blb.socket.demo2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * UDP客户端
 */
public class UDPClient {

    public void sendMessage(String ip,int port,String message){
        //创建客户端Socket
        try (DatagramSocket client = new DatagramSocket()){
            //将数据包装到数据报中
            byte[] bytes = message.getBytes();
            DatagramPacket packet = new DatagramPacket(bytes,0,bytes.length,
                    InetAddress.getByName(ip),port);
            //发送数据报
            client.send(packet);
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new UDPClient().sendMessage("192.168.1.104",8888,"Hello UDP服务器");
    }
}
